#pragma once
#include "Connection.hpp"
#include "Socket.hpp"
#include "InetAddr.hpp"
#include "Reactor.hpp"
#include "IOService.hpp"

namespace wxd
{
#define NON_BLOCK 1
    class Listen : public Connection
    {

    public:
        Listen(int port)
            : _listen_socket_ptr(std::make_unique<TcpSocket>(port)) // 创建Socket对象
        {
            // std::cout<<"port = "<<port<<std::endl;
            // 初始化Socket
            _listen_socket_ptr->TcpSocketModule();
            // 初始化Sockfd
            SetSockfd(_listen_socket_ptr->Fd());
            // 设置关心的事件
            SetEvents(EPOLLIN | EPOLLET);
        }

        virtual void Recv() override
        {
            // 接收新的连接--一定不会阻塞
            InetAddrTrans client_trans;
            int newfd = _listen_socket_ptr->Accept(client_trans);
            // 将新连接添加到Reactor
            if (newfd > 0)
            {
                std::shared_ptr<Connection> new_connect_ptr = std::make_shared<IOService>(newfd);                
                _owner->InsertConnection(new_connect_ptr);
            }
        }
        virtual void Send() override
        {
        }
        virtual void Except() override
        {
        }

    private:
        std::unique_ptr<Socket> _listen_socket_ptr;
    };
}